package app

import (
    "fmt"
    "os"
    "time"
    "math/rand"

    "git.edaijia-inc.cn/edaijia/ego/elogger"

    "github.com/go-ini/ini"
)

type GlobalConfig struct {
    Env       string `ini:"-"`
    ProxyAddr string `ini:"proxyaddr"`
    RPCAddr   string `ini:"rpcaddr"`
    Log *elogger.ELoggerConfig

    //add your config here
}

var gConfig *GlobalConfig = &GlobalConfig{
    ProxyAddr: "0.0.0.0:10000",
    RPCAddr: "127.0.0.1:10001",
    Log: &elogger.ELoggerConfig{
        Path: "./logs",
        Level: "info",
        FilePrefix: "app",
        Console: false,
    },

    //default config here
}

func InitConfig() (*GlobalConfig) {
    if len(os.Args) < 2 {
        panic("usage: bin app.conf")
    }

    cfg, err := ini.Load(os.Args[1])
    if err != nil {
        fmt.Printf("Fail to read file: %v\n", err)
        os.Exit(1)
    }

    gConfig.Env = cfg.Section("").Key("env").String()
    if gConfig.Env == "" {
        fmt.Printf("miss env in config file")
        os.Exit(1)
    }
    gConfig.ProxyAddr = cfg.Section("").Key("proxyaddr").String()
    gConfig.RPCAddr = cfg.Section("").Key("rpcaddr").String()

    err = cfg.Section(gConfig.Env+".log").MapTo(gConfig.Log)
    if err != nil {
        fmt.Printf("Fail to read config file: %v\n", err)
        os.Exit(1)
    }

    rand.Seed(time.Now().UnixNano())

    //check config here

    return gConfig
}

func GetGConfig() *GlobalConfig {
    return gConfig
}
